<template>
  <div class="questionsNew-container" ref="questionsNew_box" id="box">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? "试题修改" : "试题录入" }}</span>
      </div>

      <!-- 下面表单部分 -->
      <el-form
        ref="addQueForm"
        :model="addQueForm"
        label-width="80px"
        size="middle"
        :rules="addRules"
      >
        <!-- 学科 -->
        <el-form-item label="学科" prop="subjectID">
          <el-select
            v-model="addQueForm.subjectID"
            placeholder="请选择"
            @change="changeId"
          >
            <el-option
              v-for="items in subjectList"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->

        <el-form-item label="目录" prop="catalogID">
          <el-select v-model="addQueForm.catalogID" placeholder="请选择">
            <el-option
              v-for="items in directorysList"
              :key="items.id"
              :label="items.directoryName"
              :value="items.id"
            ></el-option>
            <!-- <el-option
              v-for="items in SimDirectorysList"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            ></el-option> -->
          </el-select>
        </el-form-item>

        <!-- 企业 -->
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="addQueForm.enterpriseID" placeholder="请选择">
            <el-option
              v-for="items in compantList"
              :key="items.id"
              :label="items.company"
              :value="items.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select
            v-model="addQueForm.province"
            placeholder="请选择"
            class="cityBox"
            @change="getcity"
          >
            <el-option
              v-for="items in provincesList"
              :key="items"
              :label="items"
              :value="items"
            ></el-option>
          </el-select>
          <el-select
            v-model="addQueForm.city"
            placeholder="请选择"
            class="cityBox"
          >
            <el-option
              v-for="items in cityList"
              :key="items"
              :label="items"
              :value="items"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-select v-model="addQueForm.direction" placeholder="请选择">
            <el-option
              v-for="items in direction"
              :key="items"
              :label="items"
              :value="items"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型" prop="questionType">
          <el-radio-group v-model="addQueForm.questionType" @change="isRadio">
            <el-radio :label="1">单选</el-radio>
            <el-radio :label="2">多选</el-radio>
            <el-radio :label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="addQueForm.difficulty">
            <el-radio :label="1">简单</el-radio>
            <el-radio :label="2">一般</el-radio>
            <el-radio :label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干" prop="question" class="editor">
          <quillEditor v-model="addQueForm.question" :options="editorOption" />
        </el-form-item>

        <el-form-item label="选项" v-if="test()">
          <div
            v-for="(items, index) in initAlphabet.slice(0, i)"
            :key="items"
            class="opBox"
          >
            <!-- 选项 -->
            <el-radio-group
              v-model="addQueForm.options[index].isRight"
              @change="isTrue($event, index)"
              v-if="addQueForm.questionType == '1'"
            >
              <el-radio :label="true">{{ items }}:</el-radio>
            </el-radio-group>

            <el-checkbox-group
              v-model="addQueForm.options[index].isRight"
              v-if="addQueForm.questionType == '2'"
            >
              <el-checkbox :label="true">{{ items }}:</el-checkbox>
            </el-checkbox-group>
            <!-- 文本框 -->
            <el-input
              v-model="addQueForm.options[index].title"
              size="small"
              class="options"
            ></el-input>
            <!-- 图片 -->
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imgURL" :src="imgURL" class="avatar" />
              <i v-else class="avatar-uploader-icon">上传图片</i>

              <i class="el-icon-circle-close del"></i>
            </el-upload>
          </div>
        </el-form-item>

        <el-button
          v-if="addQueForm.questionType == '1'"
          type="danger"
          class="add"
          size="small"
          @click="addOptions"
          disabled
          >+增加选项与答案</el-button
        >
        <el-button
          v-if="addQueForm.questionType == '2'"
          type="danger"
          class="add"
          size="small"
          @click="addOptions"
          >+增加选项与答案</el-button
        >
        <el-form-item label="解析视频" class="video">
          <el-input v-model="addQueForm.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析" prop="answer" class="editor">
          <quillEditor v-model="addQueForm.answer" :options="editorOption" />
        </el-form-item>
        <el-form-item label="题目备注">
          <el-input type="textarea" v-model="addQueForm.remarks"></el-input>
        </el-form-item>
        <el-form-item label="试题标签" prop="tags">
          <el-select
            v-model="addQueForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择文章标签"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- @click="addQue" -->
        <el-form-item>
          <el-button v-if="isEdit" type="success" size="middle" @click="addQue"
            >确认修改</el-button
          >
          <el-button v-else type="primary" size="middle" @click="addQue"
            >确认提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>

// 导入学科
import { simple } from '@/api/hmmm/subjects.js'
// 导入目录simple as simpleDir
import { list } from '@/api/hmmm/directorys.js'
// 导入企业
import { list as listCompanys } from '@/api/hmmm/companys.js'
// 导入城市
import { provinces, citys } from '@/api/hmmm/citys.js'
// 导入方向
import { direction } from '@/api/hmmm/constants.js'
// 导入题库列表 看样式 detail,add,
import { add, detail } from '@/api/hmmm/questions.js'
// 导入标签
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
// 导入token
import { getToken } from '@/utils/auth.js'
// 富文本
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  data () {
    return {

      // 表单数据
      addQueForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: 1,
        difficulty: 1,
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: ''

          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: ''

          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: ''

          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: ''

          }],
        videoURL: null,
        tags: null,
        remarks: null

      },
      // 学科数据
      subjectList: [],
      // 目录数据
      directorysList: [],
      // 简单接口目录数据
      // SimDirectorysList: [],
      // 公司列表
      compantList: [],
      // provinces 城市一级
      provincesList: [],
      // cityList 城市二级
      cityList: [],
      // 方向
      direction,
      // 定义默认4个选项
      i: 4,
      initAlphabet: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      disableVal: false,
      editorOption: {
        placeholder: '', // 占位文字
        modules: {
          // 工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },

      // 获取标签
      tagOptions: [],

      // 表单验证
      addRules: {
        subjectID: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        province: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        city: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        question: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      },
      imgURL: '',

      // isEdit 判断是否为编辑状态
      isEdit: false,
      // 图片上传header
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    }
  },
  created () {
    // 调用获取学科列表
    this.getSubList()

    // 调用获取简单目录列表
    // this.getSimDirList()
    // 调用公司列表
    this.getCompanysList()
    // 获取城市列表一级
    this.provincesList = provinces()

    this.getTag()

    // 获取文章ID  开启编辑状态
    // this.$route.params.id = 41

    if (this.$route.params.id) {
      // 文章编辑
      this.isEdit = true
      // 编辑状态：获取详情
      this.getDetail()
    }
  },
  methods: {

    handleAvatarSuccess (res, file, item) {
      console.log(res, file, item)
    },

    // // 获取详情
    async getDetail () {
      const data = {
        id: this.$route.params.id
      }
      console.log(data)
      const res = await detail(data)
      // 处理数据：
      // 让选项与返回值对应
      this.i = res.data.options.length
      // 正确答案格式匹配
      res.data.options.forEach(item => {
        if (item.isRight === 1) {
          item.isRight = true
        }
      })
      res.data.tags = res.data.tags.split(',')
      // css3,bfc".split(',')
      // 将选项类型转换成数字
      res.data.questionType = parseInt(res.data.questionType)
      res.data.difficulty = parseInt(res.data.difficulty)
      this.addQueForm = res.data

      this.getDirList()
      // 页面跳转
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },

    // 添加试题add
    addQue () {
      // 数据格式转换
      this.addQueForm.tags = this.addQueForm.tags.join(',')
      this.addQueForm.questionType = this.addQueForm.questionType.toString()
      this.addQueForm.difficulty = this.addQueForm.difficulty.toString()
      this.addQueForm.options.forEach(item => {
        if (item.isRight === true) {
          item.isRight = 1
        } else {
          item.isRight = 0
        }
      })
      // 表单验证
      this.$refs.addQueForm.validate(async (valid) => {
        console.log(valid)
        if (valid) {
          // 发起请求
          try {
            await add(this.addQueForm)
            this.$message.success('操作成功')
            this.$router.push('/questions/list')
          } catch (error) {
            console.log(error)
            this.$message.error('操作失败')
          }
        } else {
          this.$message.error('填写表单必填项')
          return false
        }
      })
    },

    // 判断简单时隐藏选项功能
    test: function () {
      if (this.addQueForm.questionType === 3) {
        return false
      }
      return true
    },

    // 获取学科列表
    async getSubList () {
      try {
        const { data } = await simple()
        this.subjectList = data
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    // 点击学科列表获取当前value值
    changeId (i) {
      // 赋值
      this.addQueForm.subjectID = i
      // 调用接口返回对应学科的数据
      this.getDirList()
    },

    // 获取目录列表
    async getDirList () {
      // isEdit: false

      try {
        // 设置参数
        const data = {
          subjectID: this.addQueForm.subjectID
        }
        const { data: { items } } = await list(data)
        // 将数据赋值给data数据
        this.directorysList = items
      } catch (error) {
        this.$message.error('操作失败')
      }
    },

    // // 获取目录简单列表中的数据
    // async getSimDirList () {
    //   try {
    //     const { data } = await simpleDir()
    //     this.SimDirectorysList = data
    //     console.log(this.SimDirectorysList)
    //   } catch (error) {
    //     this.$message.error('操作失败')
    //   }
    // },
    // 获取公司
    async getCompanysList () {
      const { data: { items } } = await listCompanys()
      this.compantList = items
    },

    // 获取二级城市
    getcity (i) {
      // 再次点击时清除二级联动表单数据
      this.addQueForm.city = ''
      this.cityList = citys(i)
    },
    // 图片上传
    // handleAvatarSuccess (res, file) {
    //   this.imgUrl = URL.createObjectURL(file.raw)
    // },

    // 点击按钮添加选项
    addOptions () {
      if (this.i === 6) {
        return false
      }
      this.i++
      this.addQueForm.options.push({
        code: 'initAlphabet[i]',
        title: '',
        img: '',
        isRight: ''

      })
    },
    // 排他思想，去掉其他单选框状态
    isTrue (e, indexCur) {
      if (this.addQueForm.questionType === 1) {
        this.initAlphabet.slice(0, this.i).forEach((item, index) => {
          this.addQueForm.options[index].isRight = ''
        })
        this.addQueForm.options[indexCur].isRight = e
      }
    },
    // 当从多选切换为单选时，恢复默认4个选项，及前四个选中状态
    isRadio (e) {
      if (e === 1) {
        this.initAlphabet = this.initAlphabet.slice(0, 4)
        // 遍历清除选中状态
        this.initAlphabet.forEach((item, index) => {
          this.addQueForm.options[index].isRight = ''
        })
      }
    },
    // 获取标签tagsSimple
    async getTag () {
      const { data } = await tagsSimple()
      this.tagOptions = data
    }

  },

  components: { quillEditor }

}
</script>

<style scoped lang='less'>
// .questionsNew-container {
//   position: relative;
//   top: 0;
//   left: 0;
//   height: 2000px;
//   overflow: auto;
// }
.el-card {
  margin: 10px;

  .el-select {
    width: 35%;
  }
  .cityBox {
    margin-right: 5px;
    width: 17.2%;
  }
  .options {
    width: 20%;
    margin-left: 10px;
  }

  .opBox {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    // overflow: hidden;
    margin-left: 5px;
    width: 95px;
    height: 60px;

    i {
      font-style: normal;
      font-size: 15px;
    }
    .del {
      position: absolute;
      right: -10px;
      top: -10px;
      color: #999;
      font-size: 20px;
    }
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 95px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 95px;
    height: 60px;
    display: inline-block;
  }
  .add {
    margin-left: 80px;
  }
  .editor {
    /deep/ .el-form-item__content {
      line-height: normal;
    }
    /deep/.ql-editor {
      height: 200px;
    }
  }
  .video {
    width: 39%;
    margin-top: 20px;
  }
  .el-textarea {
    width: 35%;
    margin-bottom: 30px;

    .el-textarea__inner {
      height: 100px !important;
    }
  }
}
</style>
